class Blast < ActiveRecord::Base
  cattr_accessor :partials
  @@partials = nil
  
  acts_as_blast
  attr_accessor :_blasted, :recipients
  
  belongs_to :blasted, :polymorphic => true
  belongs_to :user
  validates_presence_of :user_id, :to, :from

  def validate_on_create
    if self.blasted_id.nil? and self.blasted_type.nil?
       errors.add_to_base("blasted_id, blasted_type & partial are all nil. you must set either partial or blasted_id/blasted_type")        if self.partial.nil?    
    end
    if self.user_id.nil?
        # this is just-in-case something like this User.new.blast!
        errors.add_to_base("missing a user_id") 
     else
        errors.add_to_base("user_id not > 0") unless self.user_id > 0
     end
  end
  
  # call this to associate a blasted model... 
  def this(obj=nil, options={})
    if obj
      self.blasted_id = obj.id 
      self.blasted_type = obj.class.to_s  
      self.partial = obj.class.to_s.camelize.underscore
    else
      self.blasted_id = 0
      self.blasted_type = nil
    end
    # set the partial only if it contains something...
    self.partial = options[:partial].camelize.underscore if options[:partial]
  end 

  # check to see the if the partial provided actually exists on disk
  def partial_exists?
   key = File.join(File.dirname(__FILE__).gsub(/models/,"views/blast_mailer"), "_#{partial!}.rhtml") 
   @@partials = {} if @@partials.nil?
   if @@partials.has_key?(key)
     return true
   else
      if File.exists?(key)
        @@partials[key] = true
        return true
      end
   end
   return false 
 end
  
  # return the name of the partial just-in-case one wasn't supplied
  def partial!
   file_name = ""
   if self.partial
      file_name = self.partial
    else
      file_name = self.blasted_type.camelize.underscore.downcase if self.blasted_type
   end
   return file_name
  end

  # return the loaded associated model
  def blasted
    if self.blasted_type
      self._blasted = self.blasted_type.camelize.constantize.find(self.blasted_id) if !self._blasted
    end
    return self._blasted if self._blasted
    return nil
  end

  # grab all the distinct recipients previously emailed by this user... 
  def past_recipients(user_id=nil)
    return @recipients if user_id.nil?
    if !@recipients
      @recipients = Blast.find(:all, :select=>"DISTINCT blasts.to", :conditions=>["user_id = ?", user_id], :order=>"blasts.to ASC")
      out = []
      for blast in @recipients
        out.push(blast.to)
      end
      @recipients = out.join(", ")
    end
    @recipients
  end

  # return the flash message associated with this partial...
  def flash_message
    message = "No Blast Config Loaded!"    
    
    if Config::CONFIG["blasts"]
      config = Config::CONFIG["blasts"]
      message = config[self.partial!]['flash'] if config[self.partial!]
      if config['default'] and message == "default" 
        message = config['default']['flash'] 
      end
    end
    
    return message.strip
  end


end
